package com.wm.machine.baselibrary.common.widget.recyclerview.itemdecoration;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Copyright
 * author zhengcheng
 * date 2018/2/12
 * describe
 * history
 */

public class LinearEntrust extends RecyclerView.ItemDecoration {
  private int leftRight;
  private int topBottom;
  private int mColor;
  private Paint mPaint;

  public LinearEntrust(int leftRight, int topBottom, int mColor) {
    this.leftRight = leftRight;
    this.topBottom = topBottom;
    this.mColor = mColor;
    mPaint = new Paint();
    mPaint.setColor(mColor);
  }

  @Override
  public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDraw(c, parent, state);
    int left = 0;
    int right = 0;
    int top = 0;
    int bottom = 0;
    if (mColor == 0 || parent.getChildCount() == 0) {
      return;
    }
    LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
    if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
      for (int i = 0; i < parent.getChildCount(); i++) {
        View itemView = parent.getChildAt(i);
        left = parent.getLeft() + parent.getPaddingLeft();
        right = parent.getRight() - parent.getPaddingRight();
        top = itemView.getTop() - topBottom;
        bottom = itemView.getTop();
        if (parent.getChildAdapterPosition(itemView) != 0) {
          c.drawRect(left, top, right, bottom, mPaint);
        }
      }
    } else {
      for (int i = 0; i < parent.getChildCount(); i++) {
        View itemView = parent.getChildAt(i);
        left = itemView.getLeft() - leftRight;
        right = itemView.getLeft();
        top = parent.getTop() + parent.getPaddingTop();
        bottom = parent.getBottom() - parent.getPaddingBottom();
        if (parent.getChildAdapterPosition(itemView) != 0) {
          c.drawRect(left, top, right, bottom, mPaint);
        }
      }
    }
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);
    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) parent.getLayoutManager();

    if (linearLayoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
      if (parent.getChildAdapterPosition(view) != 0) {
        outRect.top = topBottom;
      }
      outRect.left = leftRight;
    } else {
      if (parent.getChildAdapterPosition(view) != 0) {
        outRect.left = leftRight;
      }
      outRect.top = topBottom;
    }
  }

}
